package com.jing.weibo.controller.pb;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.DataCons;
import com.jing.system.comm.contants.StringCons;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.RuleType;
import com.jing.system.utils.PointCurrencyUtil;
import com.jing.weibo.pojo.pb.PbTypeSeat;
import com.jing.weibo.pojo.pb.PbUserTypeSeat;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.pb.PbTypeSeatService;
import com.jing.weibo.service.pb.PbUserTypeSeatService;
import com.jing.weibo.service.system.StationletterService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.ws.sina.TimelineService;

/**
 * 泡吧用户分区位置的Controller
 * @author jing.yue
 * @version 2012/09/29 1.0.0
 */
@Controller
public class PbUserTypeSeatController extends BaseController {

	private static final Logger logger = Logger.getLogger(PbUserTypeSeatController.class);

	@Autowired
	private TimelineService timelineService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private PbTypeSeatService pbTypeSeatService;
	@Autowired
	private PbUserTypeSeatService pbUserTypeSeatService;
	@Autowired
	private StationletterService stationletterService;

	/**
	 * 添加泡吧用户分区位置信息[强占或占领]
	 * @return
	 */
	@RequestMapping(value = "/pbUserTypeSeat/json/addPbUserTypeSeat")
	@ResponseBody
	public ModelMap addPbUserTypeSeat(HttpServletRequest request, PbUserTypeSeat pbUserTypeSeat) {
		String result = null;
		Integer pbUserTypeSeatid = null;
		UserInfo userInfo = getSessionUser(request);
		StringBuffer errorWeiboMsg = new StringBuffer();

		//判断用户是否开启互粉
		if(userInfo.getIsopenmp().intValue() == 0) {
			result = ERROR_ISOPENMP;
		}
		//判断用户妞币数是否为0
		else if((userInfo.getCurrency() - pbUserTypeSeat.getCurrency()) < 0) {
			result = "currency_is_null";
		}
		else {
			try {
				pbUserTypeSeat.setUsername(userInfo.getUsername());
				PbTypeSeat pbTypeSeat = pbTypeSeatService.findByIdPbTypeSeat(pbUserTypeSeat.getTypeseatid());
				pbUserTypeSeat.setTypeid(pbTypeSeat.getTypeid());

				//判断在该分区下是否存在一个位置
				PbUserTypeSeat puts = pbUserTypeSeatService.findByUsernameTypeidPuts(pbUserTypeSeat);
				if(puts != null) {
					pbUserTypeSeatid = puts.getId();
					result = "exist_seat";
				}
				else {
					pbUserTypeSeatService.savePbUserTypeSeat(pbUserTypeSeat);

					//区分是否为占领或强占[0占领/1强占]
					if(pbUserTypeSeat.getCapturetype().intValue() == 0) {
						timelineService.updateStatus(WeiboCons.weibo_info_invite_capture_content, userInfo.getToken());
					}
					else if(pbUserTypeSeat.getCapturetype().intValue() == 1) {
						//根据用户名和位置ID修改非当前用户的信息为删除状态
						pbUserTypeSeatService.updatePbUserTypeSeatToLog(pbUserTypeSeat);
						//发送微博信息给被抢占人
						UserInfo user = userInfoService.findByUserName(pbUserTypeSeat.getCaptureusername());
						timelineService.updateStatus(SystemCons.getCaptureContent(user.getNickname()), userInfo.getToken());

						String content = String.format(StringCons.STATIONLETTER_SEAT_USER_CAPTURE_CONTENT, userInfo.getNickname(), DataCons.pbTypeMap.get(pbTypeSeat.getTypeid()).getName(), pbTypeSeat.getName());
						//发送站内信通知
						stationletterService.saveStationletter(StringCons.STATIONLETTER_SEAT_USER_CAPTURE_TITLE, content, user.getUsername(), WeiboCons.system_weiboId, user.getNickname());
					}

					//购买一个位置
					PointCurrencyUtil pointCurrencyUtil = new PointCurrencyUtil(RuleType.TYPE_PURCHASE_SEAT, userInfo.getUsername(), pbUserTypeSeat.getCurrency().intValue());
					pointCurrencyUtil.handlePointCurrency();
					//同步Session中的用户信息
					setSessionUser(request, userInfoService.findByUserName(userInfo.getUsername()));

					result = SUCCESS;
				}
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
			} catch (Exception e) {
				result = ERROR;
				logger.error(userInfo.getNickname() + ": 添加泡吧用户分区位置异常!", e);
			}
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		modelMap.put("result", result);
		modelMap.put("pbUserTypeSeatid", pbUserTypeSeatid);
		modelMap.put("currency", userInfo.getCurrency());
		return modelMap;
	}

	/**
	 * 取消泡吧用户分区位置信息
	 * @return
	 */
	@RequestMapping(value = "/pbUserTypeSeat/json/cancelPbUserTypeSeat")
	@ResponseBody
	public ModelMap cancelPbUserTypeSeat(HttpServletRequest request, PbUserTypeSeat pbUserTypeSeat) {
		String result = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			pbUserTypeSeat.setUsername(userInfo.getUsername());

			pbUserTypeSeatService.updatePbUserTypeSeatUsernameIdToLog(pbUserTypeSeat);

			result = SUCCESS;
		} catch (Exception e) {
			result = ERROR;
			logger.error(userInfo.getNickname() + ": 添加泡吧用户分区位置异常!", e);
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 修改泡吧用户分区位置信息
	 * @return
	 */
	@RequestMapping(value = "/pbUserTypeSeat/json/updatePbUserTypeSeat")
	@ResponseBody
	public ModelMap updatePbUserTypeSeat(HttpServletRequest request, PbUserTypeSeat pbUserTypeSeat) {
		String result = null;
		UserInfo userInfo = getSessionUser(request);

		try {
			//判断用户是否开启互粉
			if(userInfo.getIsopenmp().intValue() == 0) {
				result = ERROR_ISOPENMP;
			}
			PbUserTypeSeat userTypeSeat = pbUserTypeSeatService.findByIdPbUserTypeSeat(pbUserTypeSeat.getId());
			Float diffCurrency = pbUserTypeSeat.getCurrency() - userTypeSeat.getCurrency();
			//判断用户妞币数是否为0
			if((userInfo.getCurrency() -  diffCurrency) < 0) {
				result = "currency_is_null";
			}
			else {
				pbUserTypeSeat.setUsername(userInfo.getUsername());
				pbUserTypeSeatService.updatePbUserTypeSeat(pbUserTypeSeat);

				//购买一个位置
				if(diffCurrency.intValue() > 0) {
					PointCurrencyUtil pointCurrencyUtil = new PointCurrencyUtil(RuleType.TYPE_PURCHASE_SEAT, userInfo.getUsername(), diffCurrency.intValue());
					pointCurrencyUtil.handlePointCurrency();
					//同步Session中的用户信息
					setSessionUser(request, userInfoService.findByUserName(userInfo.getUsername()));
				}
				result = SUCCESS;
			}
		} catch (Exception e) {
			result = ERROR;
			logger.error(userInfo.getNickname() + ": 修改泡吧用户分区位置异常!", e);
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("currency", userInfo.getCurrency());
		return modelMap;
	}

	/**
	 * 获取泡吧分区位置用户信息列表
	 * @return
	 */
	@RequestMapping(value = "/pbUserTypeSeat/json/findPbUserTypeSeat")
	@ResponseBody
	public ModelMap findPbUserTypeSeat(HttpServletRequest request, PbUserTypeSeat pbUserTypeSeat) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			pbUserTypeSeat.setUsername(userInfo.getUsername());
			map = pbUserTypeSeatService.findPbUserTypeSeat(pbUserTypeSeat);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 获取获取泡吧分区位置用户列表异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 跳转到用户泡吧分区位置记录页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toPbUserTypeSeatManager")
	public String toPbUserTypeSeatManager(HttpServletRequest request, ModelMap modelMap) {
		return "user/pb/mypbtypeseatlog_manager";
	}

	/**
	 * 根据用户名获取用户泡吧分区位置列表信息
	 * @return
	 */
	@RequestMapping(value = "/pbUserTypeSeat/json/findByUsernamePuts")
	@ResponseBody
	public ModelMap findByUsernamePuts(HttpServletRequest request, PbUserTypeSeat pbUserTypeSeat) {
		String result = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			pbUserTypeSeat.setUsername(userInfo.getUsername());
			map = pbUserTypeSeatService.findByUsernamePuts(pbUserTypeSeat);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 获取用户泡吧分区位置列表信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		return modelMap;
	}
}